#!/usr/bin/env node

/**
 * Module dependencies.
 */

const program = require('commander');
const fs = require('fs');
const LibHelper = require('./helper');
const helper = new LibHelper();
const jsYaml = require('js-yaml')

program
    .version('1.0.0', '-v, --version')
    .requiredOption('-i, --input <path>', 'which directory yaml files need to be merged')
    .option('-o, --output <filename>', 'the output of the merged yaml file', 'tmp.yaml')
    .on('--help', function () {
        console.log('  Examples:');
        console.log();
        console.log('    $ doc -i /project/dir');
        console.log();
    })
    .parse(process.argv);

// 需要生成文档的目录
const docPath = helper.getPathByParam(program.input);
try {
    const stat = fs.statSync(docPath);
    if (!stat.isDirectory()){
        // 如果不是目录
        console.log('请指定需要合并的yaml文件目录');
        process.exit(0);
    }
} catch (e) {
    console.log(`请检查${program.input}文件夹是否存在`);
    process.exit(0);
}

// 获取目录下的所有yaml文件path
const paths = helper.getFilesPathByDir(docPath);
const yamlFilesPath = helper.getYamlFilesPath(paths);

// 合并后的文件，如果没有指定合并后的文件名，默认tmp.yaml
const outputFileName = program.output.split('.')[0] + '.yaml';
const distFile = helper.getPathByParam(outputFileName);

console.log('开始合并...');

const mergedResult = helper.merge(yamlFilesPath);
if(mergedResult) {
    const result = jsYaml.safeDump(mergedResult);
    fs.writeFileSync(distFile, result);
    console.log('合并成功！');
} else {
    console.log('没有内容需要合并'); 
}